import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import DataBase from 'src/config/database';
import { Repository, Like, UpdateResult, IsNull } from 'typeorm';
import utils from 'src/common/utils';
import { InternetCelebrityGroupCheck } from './internetCelebrityGroupCheck.entity';
import { InternetCelebrityGroup } from '../internetCelebrityGroup/internetCelebrityGroup.entity';
import { Platform } from '../platform/platform.entity';
import { InternetCelebrity } from '../internetCelebrity/internetCelebrity.entity';
import { TypeEnum } from '../platform/platform.enum';
import { EnumInternetCelebrityOverseasEnum } from '../internetCelebrity/internetCelebrity.enum';
import { video_SubAppId_List } from 'src/setting';
import { Notices } from '../notices/notices.entity';
import { NoticeTypeEnum } from '../notices/notices.enum';
import { WsStartGateway } from '../ws/ws.gateway';
import { RejectReason } from '../rejectReason/rejectReason.entity';
import { RedisCacheService } from '../redisCache/redisCache.service';
import { WxUser } from '../wxUser/wxUser.entity';
import { InternetCelebrityGroupHistory } from '../internetCelebrityGroupHistory/InternetCelebrityGroupHistory.entity';

@Injectable()
export class InternetCelebrityGroupCheckService {
  constructor(
    @InjectRepository(InternetCelebrityGroupCheck)
    private repository: Repository<InternetCelebrityGroupCheck>,
    @InjectRepository(InternetCelebrityGroup)
    private internetCelebrityGroupRepository: Repository<InternetCelebrityGroup>,
    @InjectRepository(InternetCelebrity)
    private internetCelebrityRepository: Repository<InternetCelebrity>,
    @InjectRepository(Platform)
    private platformRepository: Repository<Platform>,
    @InjectRepository(Notices)
    private noticesRepository: Repository<Notices>,
    private wsStartGateway: WsStartGateway,
    @InjectRepository(RejectReason)
    private rejectReasonRepository: Repository<RejectReason>,
    private readonly redisCacheService: RedisCacheService, 
    @InjectRepository(WxUser)
    private wxUserRepository: Repository<WxUser>,
    @InjectRepository(InternetCelebrityGroupHistory)
    private internetCelebrityGroupHistoryRepository: Repository<InternetCelebrityGroupHistory>,
    
  ) {}

  async ic_Reject(ic_group, reason_id: number){
    let findIcGroupInfo: InternetCelebrityGroup = await this.internetCelebrityGroupRepository.findOne({where:{id: ic_group}})
    if(!findIcGroupInfo){
      return '未找到平台信息'
    }
    let findReason: RejectReason = await this.rejectReasonRepository.findOne({where:{id: reason_id}})
    if(!findReason){
      return '未找到驳回原因信息'
    }

    let checkingList = await this.repository.find({where:{ic_group: ic_group}, order:{id: 'asc'}})
    let icHistory: InternetCelebrityGroupHistory[] = []
    checkingList.map(e => {
      let ithItem:InternetCelebrityGroupHistory = new InternetCelebrityGroupHistory()
      ithItem.account = e.account
      ithItem.avatar_img = e.avatar_img
      ithItem.avatar_img_id = e.avatar_img_id
      ithItem.create_time = e.create_time
      ithItem.ic_group = e.ic_group
      ithItem.name = e.name
      ithItem.platform = e.platform
      ithItem.wx_user = e.wx_user
      icHistory.push(ithItem)
    })
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //删除审核信息
      await this.repository.createQueryBuilder(null, queryRunner).delete().where({ic_group:ic_group, wx_user: findIcGroupInfo.wx_user}).execute()
      //添加通知
      let notice = new Notices()
      notice.wx_user = findIcGroupInfo.wx_user
      notice.create_time = new Date()
      notice.type = NoticeTypeEnum.platform_check_reject
      notice.reject_reason = findReason.reason
      let addNotice = await this.noticesRepository.createQueryBuilder(null, queryRunner).insert().into(Notices).values(notice).execute()
      if(addNotice.identifiers[0]){
        let notice_id = addNotice.identifiers[0].id
        icHistory.map(e => {
          e.notice_id = notice_id
        })
        await this.internetCelebrityGroupHistoryRepository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(InternetCelebrityGroupHistory)
          .values(icHistory)
          .execute()
      }

      //修改平台信息审核状态
      await this.wxUserRepository.createQueryBuilder(null, queryRunner).update({platform_checking: null}).where({openid: findIcGroupInfo.wx_user}).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();

      this.wsStartGateway.postUpdatePlatformInfo(findIcGroupInfo.wx_user)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async ic_Accept(ic_group){
    let findIcGroupInfo: InternetCelebrityGroup = await this.internetCelebrityGroupRepository.findOne({where:{id: ic_group}})
    if(!findIcGroupInfo){
      return '未找到平台信息'
    }
    let findIcList: InternetCelebrity[] = await this.internetCelebrityRepository.query(`
      select * from internet_celebrity
      where ic_group = ? and avatar_id is not null and avatar_id != ''
    `,[ic_group])
    //查找审核的答案
    let checkingList = await this.repository.find({where:{ic_group: ic_group}, order:{id: 'asc'}})

    findIcList = findIcList.filter(e => {
      if(!checkingList.find(c => c.avatar_img_id == e.avatar_id)){
        return true
      }
    })
    let findWxUser = await this.repository.query(`
      select wx_user.id as wx_user_id from wx_user
      where openid = ?
    `,[findIcGroupInfo.wx_user])
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let internet_celebrityList: InternetCelebrity[] = []
      let platformList: Platform[] = []
      let icHistory: InternetCelebrityGroupHistory[] = []
      checkingList.map(async (e: InternetCelebrityGroupCheck) => {
        let platformItem = new Platform()
        platformItem.platform = e.platform
        platformItem.create_time = new Date()
        platformItem.ic_group = ic_group
        platformItem.wx_user = findIcGroupInfo.wx_user
        platformItem.type = TypeEnum.overseas
        platformItem.wx_user = findIcGroupInfo.wx_user
        platformList.push(platformItem)

        let icItem = new InternetCelebrity()
        icItem.name = e.name
        icItem.avatar_id = e.avatar_img_id
        icItem.avatar_img = e.avatar_img
        icItem.account = e.account
        icItem.overseas = EnumInternetCelebrityOverseasEnum.overseas
        icItem.create_time = new Date()
        icItem.wx_user = findIcGroupInfo.wx_user
        icItem.ic_group = ic_group
        internet_celebrityList.push(icItem)

        let ithItem:InternetCelebrityGroupHistory = new InternetCelebrityGroupHistory()
        ithItem.account = e.account
        ithItem.avatar_img = e.avatar_img
        ithItem.avatar_img_id = e.avatar_img_id
        ithItem.create_time = e.create_time
        ithItem.ic_group = e.ic_group
        ithItem.name = e.name
        ithItem.platform = e.platform
        ithItem.wx_user = e.wx_user
        icHistory.push(ithItem)
      })

      //删除所有平台信息
      await this.platformRepository.createQueryBuilder(null, queryRunner).delete().where({ic_group: ic_group, wx_user: findIcGroupInfo.wx_user}).execute()
      //删除所有网红信息
      await this.internetCelebrityRepository.createQueryBuilder(null, queryRunner).delete().where({ic_group: ic_group, wx_user: findIcGroupInfo.wx_user}).execute()
      //添加平台信息
      let savePlatformLIst = await this.platformRepository.createQueryBuilder(null, queryRunner).insert().into(Platform).values(platformList).execute()
      savePlatformLIst.generatedMaps.map((platform,index) => {
        internet_celebrityList[index].platform = platform.id
      })
      //添加网红信息
      await this.internetCelebrityRepository.createQueryBuilder(null, queryRunner).insert().into(InternetCelebrity).values(internet_celebrityList).execute()
      //修改网红时间
      await this.internetCelebrityGroupRepository.createQueryBuilder(null, queryRunner).update({update_time: new Date()}).where({id: findIcGroupInfo.id}).execute()
      //删除审核信息
      await this.repository.createQueryBuilder(null, queryRunner).delete().where({ic_group:ic_group, wx_user: findIcGroupInfo.wx_user}).execute()
      //添加通知
      let notice = new Notices()
      notice.wx_user = findIcGroupInfo.wx_user
      notice.create_time = new Date()
      notice.type = NoticeTypeEnum.platform_check_accept
      let addNotice = await this.noticesRepository.createQueryBuilder(null, queryRunner).insert().into(Notices).values(notice).execute()
      if(addNotice.identifiers[0]){
        let notice_id = addNotice.identifiers[0].id
        icHistory.map(e => {
          e.notice_id = notice_id
        })
        await this.internetCelebrityGroupHistoryRepository.createQueryBuilder(null, queryRunner).insert().into(InternetCelebrityGroupHistory).values(icHistory).execute()
      }
      //修改平台信息审核通过
      await this.wxUserRepository.createQueryBuilder(null, queryRunner).update({platform_checking: 1}).where({openid: findIcGroupInfo.wx_user}).execute()
      
      await queryRunner.commitTransaction()
      await queryRunner.release();

      //删除缓存-网红信息
      if(findWxUser[0]?.wx_user_id){
        await this.redisCacheService.clear(`icinfo:wxuser:${findWxUser[0].wx_user_id}*`)
      }
      this.wsStartGateway.postUpdatePlatformInfo(findIcGroupInfo.wx_user)
      //删除原有头像
      let delAvatarImgIndex = 0
      if(findIcList.length > 0){
        let loopDelete = async() => {
          await utils.deleteYunRes(findIcList[delAvatarImgIndex].avatar_id, video_SubAppId_List.answer, true)
          delAvatarImgIndex++
          if(delAvatarImgIndex < findIcList.length){
            await loopDelete()
          }
        }
        await loopDelete()
      }
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async findAll_Checking(skip: number, take: number, platform_checking: number, nav_video_id?: any){
    let dataList = [], total = 0
    let pageIndex: any = ''
    if(platform_checking == 1){
      if(nav_video_id){
        let findSkip = await this.repository.query(`
          select rownumber from (
            select (@rownum:= @rownum + 1) as rownumber, video.id 
            from (SELECT @rownum := 0) t,(
              select distinct internet_celebrity_group.id
              from internet_celebrity 
              inner join platform on platform.ic_group = internet_celebrity.ic_group and platform.id = internet_celebrity.platform
              inner join internet_celebrity_group on internet_celebrity_group.id = internet_celebrity.ic_group
              inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
              where wx_user.platform_checking = 1 and internet_celebrity_group.type = 2
            ) video
          ) video
          where video.id = ?
        `,[nav_video_id])
        if(findSkip.length > 0){
          pageIndex = Math.ceil(findSkip[0].rownumber / take) - 1
          if(pageIndex <= 0) pageIndex = 0
          skip = pageIndex * take
          pageIndex = pageIndex + 1
        }
      }
      
      dataList = await this.repository.query(`
        select distinct internet_celebrity.account, internet_celebrity.name as ic_name,
          wx_user.name as wx_user_name, wx_user.avatar_img as wx_user_avatar_img, wx_user.id_card as wx_user_id_card, internet_celebrity_group.id,
          platform.platform,internet_celebrity.avatar_img,internet_celebrity.img
        from internet_celebrity 
        inner join platform on platform.ic_group = internet_celebrity.ic_group and platform.id = internet_celebrity.platform
        inner join internet_celebrity_group on internet_celebrity_group.id = internet_celebrity.ic_group
        inner join wx_user on wx_user.openid = internet_celebrity_group.wx_user
        where wx_user.platform_checking = 1 and internet_celebrity_group.type = 2
        limit ?,?
      `,[skip, take])

      total = await this.repository.query(`
        select count(1) as total
        from wx_user
        where wx_user.platform_checking = 1
      `,[])
    }else{
      dataList = await this.repository.query(`
        select distinct internet_celebrity_group_check.*, internet_celebrity_group_check.name as ic_name,
          wx_user.name as wx_user_name, wx_user.avatar_img as wx_user_avatar_img, wx_user.id_card as wx_user_id_card, internet_celebrity_group_check.ic_group as id
        from internet_celebrity_group_check
        inner join (
          select wx_user.openid, wx_user.name, wx_user.avatar_img, wx_user.id_card
          from wx_user
          inner join internet_celebrity_group_check on internet_celebrity_group_check.wx_user = wx_user.openid
          ${platform_checking == 1 ? `where wx_user.platform_checking = 1` : ``}
          limit ?,?
        ) as wx_user on wx_user.openid = internet_celebrity_group_check.wx_user
        order by internet_celebrity_group_check.id asc
      `,[skip, take])

      total = await this.repository.query(`
        select count(1) as total from (
          select distinct wx_user.openid
          from internet_celebrity_group_check
          inner join wx_user on wx_user.openid = internet_celebrity_group_check.wx_user
          ${platform_checking == 1 ? `where wx_user.platform_checking = 1` : ``}
        ) a
      `,[])
    }
    return {data: dataList, total: total[0].total, pageIndex}
  }

}
